
#include "timer0_drv.h"
#if USE_TIMER0
/**
 * @desc  : Gpio初始化
 * @date  : 2025-03-31
 * @author: AnRui
 * @note  :
 */
static void Timer0GPIOInit() {
    rcu_periph_clock_enable(RCU_GPIOA);
    gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_8);
    // rcu_periph_clock_enable(RCU_GPIOB);
    // gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_13);
}


/**
 * @desc  : timer0初始化
 * @date  : 2025-03-31
 * @author: AnRui
 * @note  :
 */
void Timer0DrvInit() {
    /* 使能定时器时钟；*/
    rcu_periph_clock_enable(RCU_TIMER0);
    /* 复位定时器；*/
    timer_deinit(TIMER0);
    timer_parameter_struct timerInitPara;
    timer_struct_para_init(&timerInitPara);
    /* 设置预分频器值；*/
    timerInitPara.prescaler = TIMER0_PSC - 1;     // 输入给计数器的时钟频率为1Mhz，周期1us
    /* 设置自动重装载值；*/
    timerInitPara.period = TIMER0_PERIOD - 1;
    timer_init(TIMER0, &timerInitPara);
    /* PWM功能*/
    timer_oc_parameter_struct ocInitPara;
    timer_channel_output_struct_para_init(&ocInitPara);
    /* 设置通道为输出功能；*/
    ocInitPara.outputstate = TIMER_CCX_ENABLE;
    ocInitPara.ocpolarity = TIMER_OC_POLARITY_HIGH;    // 有效电平
    ocInitPara.ocidlestate = TIMER_OC_IDLE_STATE_LOW;  // 空闲状态的电平
    // ocInitPara.outputnstate = TIMER_CCXN_ENABLE;
    // ocInitPara.ocnpolarity = TIMER_OCN_POLARITY_HIGH;   // 有效电平
    // ocInitPara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW; // 空闲状态的电平
    timer_channel_output_config(TIMER0, TIMER_CH_0, &ocInitPara);
    /* 设置占空比；*/
    timer_channel_output_pulse_value_config(TIMER0, TIMER_CH_0, 0);
    /* 设置通道输出PWM模式；小于*/
    timer_channel_output_mode_config(TIMER0, TIMER_CH_0, TIMER_OC_MODE_PWM0);
    timer_primary_output_config(TIMER0, ENABLE);
    /* 设置Gpio配置*/
    Timer0GPIOInit();
    /* 使能定时器；*/
    timer_enable(TIMER0);
}

/**
 * @desc  : 更新占空比
 * @date  : 2025-03-31
 * @author: AnRui
 * @param : duty - {参数说明}:
 * @note  :
 */
void Timer0Ch0UpdatePulse(float duty) {
    if (duty > 100)
        duty = 100;
    if (duty < 0)
        duty = 0;
    uint32_t count = TIMER0_PERIOD + 1;
    uint32_t pulse = count * duty / 100 - 1;
    // 计数值
    timer_channel_output_pulse_value_config(TIMER0, TIMER_CH_0, pulse);
}
#endif 
